package com.HardWare;

import com.friendlyarm.AndroidSDK.GPIOEnum;
import com.friendlyarm.AndroidSDK.HardwareControler;

import java.sql.Statement;
import java.util.Stack;

/**
 * Created by Ziji on 2017/7/14.
 */

public class ADXL345 {
    static final double ACCELERATION=16;
    static public int ADXL345_Init(int devFD)
    {
        HardwareControler.exportGPIOPin(73);//使能端口
        HardwareControler.setGPIODirection(73, GPIOEnum.OUT);//设置GPIO为输出模式
        HardwareControler.setGPIOValue(73,GPIOEnum.HIGH);
        HardwareControler.setI2CSlave(devFD,(byte)(0x53));//设置I2c通信硬件地址

        if(HardwareControler.I2CWriteByteData(devFD,(byte)0x31,(byte) 0x0B,0)<0) {
            return -1;
        } //测量范围,正负16g，13位模式
        if(HardwareControler.I2CWriteByteData(devFD,(byte)0x2C,(byte) 0x08,0)<0) {
            return -1;
        } //速率设定为12.5 参考pdf13页
        if(HardwareControler.I2CWriteByteData(devFD,(byte)0x2D,(byte) 0x08,0)<0) {
            return -1;
        } //选择电源模式   参考pdf24页
        if(HardwareControler.I2CWriteByteData(devFD,(byte)0x2E,(byte) 0x80,0)<0) {
            return -1;
        } //使能 DATA_READY 中断
        if(HardwareControler.I2CWriteByteData(devFD,(byte)0x1E,(byte) 0x00,0)<0) {
            return -1;
        }//X 偏移量 根据测试传感器的状态写入pdf29页
        if(HardwareControler.I2CWriteByteData(devFD,(byte)0x1F,(byte) 0x00,0)<0) {
            return -1;
        } //Y 偏移量 根据测试传感器的状态写入pdf29页
        if(HardwareControler.I2CWriteByteData(devFD,(byte)0x20,(byte) 0x05,0)<0) {
            return -1;
        } //Z 偏移量 根据测试传感器的状态写入pdf29页


        return 0;
    }

    static public short[] read_AXL345(int devFD)
    {
        byte[] data;
        data = new byte[6];
        for (int i=0;i<6;i++)
        {
            data[i]=(byte)HardwareControler.readByteDataFromI2C(devFD,(byte)(0x32+i));
        }
        short[] data_short;
        data_short=new short[3];
        for(int i=0;i<3;i++)
        {
            data_short[i]=change_8to16(data[i*2],data[i*2+1]);
        }
        return data_short;
    }

    static short change_8to16(byte x,byte y)
    {
        short m;
        m=(short)(((short)y<<8)|(short)(0X00FF&x));
        return m;
    }

    public static double[] get_acceleration(int devFD)
    {
        short[] data=read_AXL345(devFD);
        double[] acceleration;
        acceleration=new double[3];
        for (int i=0;i<3;i++)
        {
            acceleration[i]=(double)data[i]/256;
        }
        return acceleration;
    }

}
